package client;

import dao.SupplierDAO;
import dao.ProductDAO;
import model.Supplier;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * 供应商客户端
 */
public class SupplierClient {
    private static final String SERVER_ADDRESS = "localhost";
    private static final int SERVER_PORT = 8888;
    private static String supplierId;
    
    public static void main(String[] args) {
        try (Socket socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
             BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) {
            
            System.out.println("欢迎使用超市管理系统-供应商端");
            
            // 登录或注册
            System.out.println("1. 登录");
            System.out.println("2. 注册");
            System.out.print("请选择: ");
            String choice = stdIn.readLine();
            
            SupplierDAO supplierDAO = new SupplierDAO();
            
            if ("1".equals(choice)) {
                // 登录
                if (!login(stdIn, supplierDAO)) {
                    System.out.println("登录失败，程序退出");
                    return;
                }
            } else if ("2".equals(choice)) {
                // 注册
                if (!register(stdIn, supplierDAO)) {
                    System.out.println("注册失败，程序退出");
                    return;
                }
            } else {
                System.out.println("无效选择，程序退出");
                return;
            }
            
            // 发送角色信息给服务器
            out.println("supplier:" + supplierId);
            
            // 启动一个线程接收服务器消息
            Thread receiverThread = new Thread(() -> {
                try {
                    String response;
                    while ((response = in.readLine()) != null) {
                        System.out.println("\n服务器消息: " + response);
                        
                        // 处理补货请求
                        if (response.startsWith("restockRequest:")) {
                            String[] parts = response.split(":");
                            if (parts.length >= 4) {
                                String employeeId = parts[1];
                                String productId = parts[2];
                                String quantity = parts[3];
                                
                                System.out.print("是否确认补货 " + productId + " 数量 " + quantity + "? (y/n): ");
                                String confirm = stdIn.readLine();
                                
                                if ("y".equalsIgnoreCase(confirm)) {
                                    // 更新库存
                                    ProductDAO productDAO = new ProductDAO();
                                    productDAO.updateStock(productId, Integer.parseInt(quantity));
                                    
                                    // 通知服务器已补货
                                    out.println("restockConfirm:" + productId + ":" + quantity);
                                    System.out.println("已确认补货");
                                }
                            }
                        }
                        
                        System.out.print("请输入命令: ");
                    }
                } catch (IOException e) {
                    System.err.println("接收消息错误: " + e.getMessage());
                }
            });
            receiverThread.start();
            
            // 处理用户输入
            System.out.println("登录成功！可用命令：");
            System.out.println("1. 查看信息");
            System.out.println("2. 退出: exit");
            
            String userInput;
            while ((userInput = stdIn.readLine()) != null) {
                if ("exit".equalsIgnoreCase(userInput)) {
                    out.println(userInput);
                    break;
                } else if ("1".equals(userInput)) {
                    // 查看信息
                    Supplier supplier = supplierDAO.login(supplierId, "");
                    if (supplier != null) {
                        System.out.println("供应商ID: " + supplier.getSupplierId());
                        System.out.println("名称: " + supplier.getName());
                        System.out.println("地址: " + supplier.getAddress());
                        System.out.println("联系人: " + supplier.getContactPerson());
                        System.out.println("电话: " + supplier.getPhone());
                    } else {
                        System.out.println("查询失败");
                    }
                } else {
                    System.out.println("未知命令，请重新输入");
                }
                System.out.print("请输入命令: ");
            }
            
            receiverThread.interrupt();
            
        } catch (IOException e) {
            System.err.println("无法连接到服务器: " + e.getMessage());
        }
    }
    
    // 登录方法
    private static boolean login(BufferedReader stdIn, SupplierDAO supplierDAO) throws IOException {
        System.out.print("请输入您的供应商ID: ");
        supplierId = stdIn.readLine();
        
        System.out.print("请输入密码: ");
        String password = stdIn.readLine();
        
        Supplier supplier = supplierDAO.login(supplierId, password);
        return supplier != null;
    }
    
    // 注册方法
    private static boolean register(BufferedReader stdIn, SupplierDAO supplierDAO) throws IOException {
        System.out.print("请设置供应商ID: ");
        supplierId = stdIn.readLine();
        
        System.out.print("请输入供应商名称: ");
        String name = stdIn.readLine();
        
        System.out.print("请输入地址: ");
        String address = stdIn.readLine();
        
        System.out.print("请输入联系人: ");
        String contactPerson = stdIn.readLine();
        
        System.out.print("请输入电话: ");
        String phone = stdIn.readLine();
        
        System.out.print("请设置密码: ");
        String password = stdIn.readLine();
        
        Supplier supplier = new Supplier(supplierId, name, address, contactPerson, phone, password);
        return supplierDAO.registerSupplier(supplier);
    }
}
    